/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kungkhies.desktop.ilo.explorer;

import com.kungkhies.desktop.library.entities.Ilo;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.swing.Action;
import org.openide.actions.DeleteAction;
import org.openide.actions.PropertiesAction;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.actions.SystemAction;
import org.openide.util.lookup.Lookups;

/**
 *
 * @author clayton
 */
public class IloChildFactory extends ChildFactory<Ilo>
{
    private List<Ilo> resultList;

    public IloChildFactory(List<Ilo> resultList) {
        this.resultList = resultList;
    }

    @Override
    protected boolean createKeys(List<Ilo> list) {
        for (Ilo ilo : resultList) {
            list.add(ilo);
        }
        return true;
    }

    @Override
    protected Node createNodeForKey(Ilo c) {
        Node node = new AbstractNode(Children.LEAF, Lookups.singleton(c)) {

            @Override
            public Action[] getActions(boolean context) {
                Action[] result = new Action[]{
                    SystemAction.get(DeleteAction.class),
                    SystemAction.get(PropertiesAction.class)
                };
                return result;
            }

            @Override
            public boolean canDestroy() {
                Ilo ilo = this.getLookup().lookup(Ilo.class);
                return ilo != null;
            }

            @Override
            public void destroy() throws IOException {
                if (deleteIlo(this.getLookup().lookup(Ilo.class).getIloId())) {
                    super.destroy();
                    IloExplorerTopComponent.refreshNode();
                }
            }

        };
        node.setDisplayName(c.getIloText());
        node.setShortDescription(c.getPackage1());
        return node;
    }

    private static boolean deleteIlo(long iloId) {
        EntityManager entityManager = Persistence.createEntityManagerFactory("KungkhieEntityLibraryPU").createEntityManager();
        entityManager.getTransaction().begin();
        try {
            Ilo toDelete = entityManager.find(Ilo.class, iloId);
            entityManager.remove(toDelete);
            // so far so good
            entityManager.getTransaction().commit();
        } catch(Exception e) {
            Logger.getLogger(IloChildFactory.class.getName()).log(
                    Level.WARNING, "Cannot delete an ilo with id {0}, cause: {1}", new Object[]{iloId, e});
            entityManager.getTransaction().rollback();
        }
        return true;
    }
}
